package com.qianclass.talklive.app.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;

import com.qianclass.talklive.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;


public class ImageUtils {
	public static Map<String, Bitmap> imageMap =  Collections.synchronizedMap(new WeakHashMap<String, Bitmap>());
	
	
	public static Bitmap getDefaultBitmap(Context context) {
		BitmapDrawable drawable = (BitmapDrawable) context.getResources().getDrawable(R.drawable.defautteacherimage);
		Bitmap bitmap = drawable.getBitmap();
		float density = context.getResources().getDisplayMetrics().density;
		int width;
		if (density <= 1.5) {
			width = 250;
		}else {
			width = 300;
		}
		
		bitmap = Bitmap.createScaledBitmap(bitmap, width, width, true);
		
		return bitmap;
	}
	
	/**
	 * 插入图片
	 * @param editText
	 * @param path
	 */
	
	
	/**
	 * 压缩图片
	 * @param context
	 * @param bitmap
	 * @return
	 */
	public static Bitmap decodeBitmap(Context context, Bitmap bitmap) {
		if (null == bitmap) {
			return null;
		}
		float width = bitmap.getWidth();
		float height = bitmap.getHeight();
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		int w =  dm.widthPixels;
		int h = dm.heightPixels;
		if (width < w && height < h) {
			// 不需要压缩
			return bitmap;
		}
		float scale = 0;
		if (height > h && width < w) {
			scale = (float) h / height;
		}else {
			scale = (float) w / width;
		}
		
		Bitmap newBitmap = null;
		
		try{
			// 创建操作图片用的matrix对象
			Matrix matrix = new Matrix();
			// 缩放图片动作
			matrix.postScale(scale, scale);
			newBitmap = Bitmap.createBitmap(bitmap, 0, 0, (int) width,
					(int) height, matrix, true);
			if (!bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}catch (OutOfMemoryError e) {
			System.gc();
			System.runFinalization();
		}
		return newBitmap;
	}
	
	/**
	 *  压缩图片， 图片大小小于100kb
	 * @param image
	 * @return
	 */
	public static File compressImage(Context context, Bitmap image) {
		File file = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			int options = 100;
			while (baos.toByteArray().length / 1024 > 100) {
				options = Math.max(0, options / 2);
				if(options <= 0) {
					break;
				}
				
				baos.close();
				baos = null;
				baos = new ByteArrayOutputStream();

				image.compress(Bitmap.CompressFormat.JPEG, options, baos);
			}

			ByteArrayInputStream isBm = new ByteArrayInputStream(
					baos.toByteArray());
			baos.close();

			baos = null;

			file = saveImage(isBm);
			isBm.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			System.gc();
			System.runFinalization();
		}

		return file;
	}

	/**
	 * 质量压缩方法 1024kb
	 *
	 * @param image
	 * @return
	 */
	public static ByteArrayInputStream compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 90;

		while (baos.toByteArray().length / 1024 > 1024) { // 循环判断如果压缩后图片是否大于1024kb,大于继续压缩
			baos.reset(); // 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		//saveImage(isBm);
		//Bitmap bitmap = BitmapFactory.decodeStream(isBm);// 把ByteArrayInputStream数据生成图片
		return bais;
	}
	
	public static File saveImage(ByteArrayInputStream in) {
		String fileName = System.currentTimeMillis() + ".jpg";
		File file = new File(Environment
				.getExternalStorageDirectory() + "/Android/data/eClass_talk/" + fileName);
		FileOutputStream fout = null;
		try {
			fout = new FileOutputStream(file);
			int current = 0;
			byte[] b = new byte[1024];
			while ((current = in.read(b)) != -1) {
				fout.write(b, 0, current);
			}
			
			fout.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return file;
	}
	
	
	
	public static Bitmap getSmallBitmap(Context context, String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(context, options);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(filePath, options);
	}
	
	
	public static int calculateInSampleSize(Context context, BitmapFactory.Options options) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		int w =  dm.widthPixels;
		int h = dm.heightPixels;
		
		int inSampleSize = 1;
		
		if (width < w && height < h) {
			return 1;
		}
		
		if (height > w || width > w) {
			final int heightRatio = Math.round((float) height
					/ (float) w);
			final int widthRatio = Math.round((float) width / (float) w);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		
		return inSampleSize;
	}
	
	
	
	
	
	
	
	public static Bitmap rotaingImage(int degree, Bitmap bitmap) {
		 	//旋转图片 动作   
	       Matrix matrix = new Matrix();;  
	       matrix.postRotate(degree);  
	       // 创建新的图片   
	       Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,  
	               bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
	       return resizedBitmap;  
	}
	
	public static int readImageDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);

			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}
	
	public static String getRealPathFromURI(Context context, Uri contentUri) {
		 String filePath = null;
        String[] proj = {MediaStore.Images.Media.DATA };
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(contentUri, proj, null, null, null);
        if (cursor != null) {  
            cursor.moveToFirst();
            filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
        }
        
        return filePath;
    } 
	
	public static void clearCache() {
		
		for(String s : imageMap.keySet()) {
			Bitmap bitmap = imageMap.get(s);
			bitmap.recycle();
		}
		imageMap.clear();
		System.gc();
		System.runFinalization();
	}


	public static Bitmap byteToBitmap(byte[] imgByte) {
		InputStream input = null;
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 8;
		input = new ByteArrayInputStream(imgByte);
		SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(
				input, null, options));
		bitmap = (Bitmap) softRef.get();
		if (imgByte != null) {
			imgByte = null;
		}

		try {
			if (input != null) {
				input.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
	}

}
